package com.njzxw.fs.commonutil.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Time;
import java.util.concurrent.TimeUnit;

@Service
public class RedisUtil {

    public org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StringRedisTemplate template;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    public void setKey(String key, String value, Long time, TimeUnit timeUnit){
        template.opsForValue().set(key,value,time,timeUnit);
    }

    public boolean deleteKey(String key){
        if(template.hasKey(key)){
            return template.delete(key);
        }
        return true;
    }

    public <T>T getValue(String key,Class<T> valueType){
        Object objs = "";
        try{
            if(!StringUtils.isBlank(key)){
                objs = template.opsForValue().get(key);
                objs = objs == null?null:(T)objs;
            }else{
                return null;
            }
        }catch (Exception e){
            logger.error("获取rediskey错误："+key,e);
            return (T)new String("");
        }finally {
            return objs == null?null:(T)objs;
        }
    }

    public void setKeyObject(String key, Object value, Long time, TimeUnit timeUnit){
        redisTemplate.opsForValue().set(key,value,time,timeUnit);
    }

    public boolean deleteKeyObject(String key){
        if(redisTemplate.hasKey(key)){
            return redisTemplate.delete(key);
        }
        return true;
    }

    public <T>T getValueObject(String key,Class<T> valueType){
        Object objs = "";
        try{
            if(!StringUtils.isBlank(key)){
                objs = redisTemplate.opsForValue().get(key);
                objs = objs == null?null:(T)objs;
            }else{
                return null;
            }
        }catch (Exception e){
            logger.error("获取rediskey错误："+key,e);
        }finally {
            return objs == null?null:(T)objs;
        }
    }

}
